﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NhanAi.Entity;
using NhanAi.DAO;
using NhanAi.DAO.Mix;
using Home.Utils;
using NhanAi.App_Code;
using System.Web.Configuration;
namespace NhanAi.Admin
{
    public partial class EditPost : BasePage
    {
        string imageUrl;

        List<Taxonomy> taxonomies;
        List<Taxonomy> cTaxonomies;
        public string ImageUrl { get { return imageUrl; } }
        public List<Taxonomy> Taxonomies { get { return taxonomies; } }

        protected void Page_Load(object sender, EventArgs e)
        {
            Authenticate();
            if (!IsPostBack)
            {
                int id = TypeWrapper.GetInt32(Request["id"]);
                PostModel daoPost = new PostModel();
               
                Post p = daoPost.Read(id, NAConstants.ALL_LANGUAGE);
                hdnId.Value = id.ToString();
                txtTitle.Text = p.Title;
                txtTitleEn.Text = p.TitleEn;
                PostContent.Value = p.Content;
                PostContentEn.Value = p.ContentEn;
                this.imageUrl = p.Guid;
               
                this.cTaxonomies = p.Taxonomies;
                cmbStatus.Items.Add(new ListItem("Nháp", NAConstants.POST_STA_DRAFT.ToString()));
                cmbStatus.Items.Add(new ListItem("Cho phép đăng", NAConstants.POST_STA_POST.ToString()));
                chkProtected.Checked = p.Protected;
                pstAttribute.PostAtt = p.PostAttribute;
                int index = 0;
                foreach (ListItem item in cmbStatus.Items)
                {
                    if (item.Value == p.Status.ToString())
                    {
                        cmbStatus.SelectedIndex = index;
                    }
                    index++;
                }
                if (!IsPostBack)
                {
                    TaxonomyDao daoTax = new TaxonomyDao();
                    this.taxonomies = daoTax.ReadAll();
                    rptTaxonomies.DataSource = taxonomies;
                    rptTaxonomies.DataBind();
                }
            }
            SetCurrentPage("Post");
        }
        public void btnUpdateClick(object sender, EventArgs e)
        {
            try
            {
                PostDao daoPost = new PostDao();
                PostModel modPost = new PostModel();
                int id = TypeWrapper.GetInt32(hdnId.Value);
                Post p = daoPost.Read(id, NAConstants.ALL_LANGUAGE);

                p.Title = txtTitle.Text;
                p.TitleEn = txtTitleEn.Text;
                p.Content = PostContent.Value;
                p.ContentEn = PostContentEn.Value;
                p.Status = int.Parse(cmbStatus.SelectedItem.Value);
                p.PostAttribute = TypeWrapper.GetInt32(Request["ThuocTinh"]);
                p.ModifiedDate = DateTime.Now;
                p.Protected = chkProtected.Checked;
                p.Guid = Request["txtImage"] == null ? "" : Request["txtImage"];
                imageUrl = p.Guid;
                p.Excerpt = StringUltility.GetExcerpt(p.Content, NAConstants.EXCERPT_LEN);
                p.ExcerptEn = StringUltility.GetExcerpt(p.ContentEn, NAConstants.EXCERPT_LEN);
                //  if (p.Excerpt.Length > NAConstants.EXCERPT_LEN) p.Excerpt.Substring(0, NAConstants.EXCERPT_LEN);
                //  if (p.ExcerptEn.Length > NAConstants.EXCERPT_LEN) p.ExcerptEn.Substring(0, NAConstants.EXCERPT_LEN);
                string taxIds = Request["taxonomy"];
                if (!String.IsNullOrEmpty(taxIds))
                {
                    List<Taxonomy> selectedTaxs = new List<Taxonomy>();
                    string[] data = taxIds.Split(',');
                    foreach (string d in data)
                    {
                        Taxonomy t = new Taxonomy(TypeWrapper.GetInt32(d));
                        selectedTaxs.Add(t);
                    }
                    p.Taxonomies = selectedTaxs;
                }
                pstAttribute.PostAtt = p.PostAttribute;
                modPost.Update(p);
                if (p.Status == NhanAi.App_Code.NAConstants.POST_STA_POST && chkSendMail.Checked)
                {
                    SendNotificationEmail(p);
                    chkSendMail.Checked = false;
                }
            }
            catch (Exception ex)
            {
                SetMessage("Đã xảy ra lỗi", "");
            }
            SetMessage("Cập nhật thành công", "");
        }
        public bool HasTaxonomy(int tId)
        {
            foreach (Taxonomy t in cTaxonomies)
            {
                if (t.Id == tId) return true;
            }
            return false;
        }
        public void SendNotificationEmail(Post p)
        {
            UserDao dao = new UserDao();
            List<string> emails = dao.GetFollowedEmails(15);
            if (emails.Count > 0)
            {
                try
                {
                    string uid = WebConfigurationManager.AppSettings["email_uid"];
                    string pwd = WebConfigurationManager.AppSettings["email_password"];
                    string server = WebConfigurationManager.AppSettings["email_server"];
                    string port = WebConfigurationManager.AppSettings["email_port"];
                    string name = WebConfigurationManager.AppSettings["email_name"];
                    string postUrl = WebConfigurationManager.AppSettings["post_url"];
                    KTEmail mailer = new KTEmail(server, Home.Utils.TypeWrapper.GetInt32(port), uid, pwd, name);
                    foreach (string em in emails)
                    {
                        mailer.Reciepients.Add(em);                        
                    }
                    string title = "Nhan Ai clinic: New post - Bài viết mới";
                    string body = "Một bài viết mới được đăng tại website của NhanAiClinic, vui lòng nhấp vào liên kết bên dưới để xem."
                        + "<br/>"
                        + "<a href='" + postUrl + "?id=" + p.Id + "'>" + (p.Title != "" ? p.Title : "Nhấp vào đây") + "</a><br/>"
                        + "(There is a new post on NhanAiClinic's website), please click followed link to view the post)<br/>"
                        + "<a href='" + postUrl + "?id=" + p.Id + "'>" + (p.TitleEn != "" ? p.TitleEn : "Click here") + "</a><br/>";
                    mailer.SendMailAsync(title, body);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }
        }
    }
}